package org.notes.multi;

import lombok.SneakyThrows;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo2 {
    //    2. 线程顺序执行：使用join()方法确保三个线程按T1→T2→T3的顺序执行。
    //可以使用线程池newSingleThreadExecutor 来控制线程顺序执行
    //CompletableFuture.thenRun 和thenRunAsync方法来控制线程顺序执行
    // CountDownLatch辅助类来控制线程顺序执行
    @SneakyThrows
    public static void main(String[] args) {
        ExecutorService es = Executors.newSingleThreadExecutor();
        MyThread t1 = new MyThread("t1");
        MyThread t2 = new MyThread("t2");
        MyThread t3 = new MyThread("t3");
        MyThread t4 = new MyThread("t4");
//        t1.start();
//        t1.join();
//        t2.start();
//        t2.join();
//        t3.start();
//        t3.join();
//        t4.start();
//        t4.join();
        es.submit(t1);
        es.submit(t2);
        es.submit(t3);
        es.submit(t4);
        es.shutdown();
    }
}

class MyThread extends Thread {
    private String threadName;

    public MyThread(String name) {
        threadName = name;
    }

    @Override
    public void run() {
        System.out.println("线程  " + threadName + "  执行了");
    }
}